package net.pws.common.httpclient;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.message.BasicNameValuePair;

public class DefaultHttpClientRequest implements HttpClientRequest {
    
    protected List<NameValuePair> params = new ArrayList<NameValuePair>();
    
    protected Properties headers = new Properties();
    
    protected String url;
    
    protected String charset = "UTF-8";
    
    public DefaultHttpClientRequest() {
        super();
    }
    
    /**
     * 带参数的构建
     * 
     * @param url
     * @param charset
     */
    public DefaultHttpClientRequest(String url, String charset) {
        super();
        this.url = url;
        this.charset = charset;
    }
    
    public HttpEntity getEntity() {
        try {
            return new UrlEncodedFormEntity(params, charset);
        }
        catch (UnsupportedEncodingException e) {
            throw new RuntimeException("构造请求参数时出错！", e);
        }
    }
    
    public String getUrl() {
        return url;
    }
    
    public Properties getHeaders() {
        return headers;
    }
    
    public void setUrl(String url) {
        this.url = url;
    }
    
    public void setParams(List<NameValuePair> params) {
        this.params = params;
    }
    
    public void setCharset(String charset) {
        this.charset = charset;
    }
    
    public String getUrlWithParams() {
        StringBuilder result = new StringBuilder(url);
        if (result.indexOf("?") < 0) {
            result.append("?");
        }
        
        if (params == null) {
            return result.toString();
        }
        
        for (int i = 0; i < params.size(); i++) {
            if (i == 0) {
                if (result.indexOf("?") + 1 < result.length() || result.lastIndexOf("&") + 1 < result.length()) {
                    result.append("&");
                }
            }
            else {
                result.append("&");
            }
            
            NameValuePair pair = params.get(i);
            result.append(pair.getName()).append("=").append(pair.getValue());
        }
        return result.toString();
    }
    
    /**
     * 增加一组参数
     * 
     * @param name
     *            参数名
     * @param value
     *            参数值
     */
    public void addParameter(String name, String value) {
        if (value == null) {
            value = "";
        }
        params.add(new BasicNameValuePair(name, value));
    }
    
    public void addHeader(String name, String value) {
        headers.put(name, value);
    }
    
}
